package com.gf.common;

import java.security.MessageDigest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import sun.misc.BASE64Encoder;

/**
 * 
 * @describe MD5加密工具类
 * @author   sss
 * @date     2014年9月5日
 */
public class Md5Encryption {
	
	private static final Logger LOGGER = LoggerFactory.getLogger(Md5Encryption.class);

	private static Md5Encryption instance = null;
	
	private Md5Encryption() {
		
	}
	
	public static Md5Encryption getInstance() {
		if(null == instance) {
			instance = new Md5Encryption();
		}
		return instance;
	}
	
	/**
	 * 
	 * @describe md5加密
	 * @param str
	 * @return
	 */
	public String md5Encode(String str) {
		MessageDigest md = null;
		String result = "";
		try {
			md = MessageDigest.getInstance("MD5");
			md.update(str.getBytes("UTF-8"));
			BASE64Encoder b = new BASE64Encoder();
			result = b.encode(md.digest());
		} catch (Exception e) {
			LOGGER.error("Md5加密异常：", e);
		}
		return result;
	}
	
	//短息接口  md5加密方式
	private final static char[] hexDigits = { '0', '1', '2', '3', '4', '5',
		'6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
	
	public String getMd5String(String strSrc) {
		try {
			//  确定计算方法
			MessageDigest md5 = MessageDigest.getInstance("MD5");
			// 加密后的字符串
			return bytes2hex(md5.digest(strSrc.getBytes()));
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}
	
	private static String bytes2hex(byte[] bytes) {
		StringBuffer sb = new StringBuffer();
		int t;
		for (int i = 0; i < 16; i++) {// 16 == bytes.length;
			t = bytes[i];
			if (t < 0)
				t += 256;
			sb.append(hexDigits[(t >>> 4)]);
			sb.append(hexDigits[(t % 16)]);
		}
		return sb.toString();
	}
}
